import React, { Component } from "react";
import { Button, Space, Table, Tag, Row, Col, Modal } from "antd";
import CategoryForm from "./components/category-form";
import { categoryGet } from "../../api/course";
const columns = [
  {
    title: "父类ID",
    dataIndex: "parentId",
    key: "parentId",
    render: (text, record, index) => {
      return text == "0-0" ? "顶级类目" : "";
    },
  },
  {
    title: "分类名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "操作",
    key: "action",
    render: (_, record) => (
      <Space size="middle">
        <Button type="primary" size="small">
          编辑
        </Button>
        <Button type="primary" danger size="small">
          删除
        </Button>
      </Space>
    ),
  },
];

export default class Category extends Component {
  state = {
    isOpen: false,
    cateList: [],
  };
  componentDidMount() {
    categoryGet(true).then((res) => {
      let cateList = this.dataToTree(res.data.results);
      this.setState({ cateList });
    });
  }
  dataToTree = (data) => {
    let parentList = data.filter((item) => item.parentId == "0-0");
    parentList.forEach((item) => {
      let children = data.filter((child) => item.objectId == child.parentId);
      if (children.length) {
        item.children = children;
      }
    });
    return parentList;
  };
  handleModal = (isOpen) => {
    this.setState({
      isOpen,
    });
  };
  render() {
    let { isOpen } = this.state;
    return (
      <>
        <Row justify="end">
          <Col span={3}>
            <Button
              type="primary"
              onClick={() => {
                this.handleModal(true);
              }}
            >
              新增分类
            </Button>
          </Col>
        </Row>
        <Modal
          title="新增分类"
          open={isOpen}
          cancelText="取消"
          okText="提交"
          onOk={() => {
            this.handleModal(false);
          }}
          onCancel={() => {
            this.handleModal(false);
          }}
          footer={null}
        >
          <CategoryForm />
        </Modal>

        <Table
          columns={columns}
          dataSource={this.state.cateList}
          rowKey="objectId"
        />
      </>
    );
  }
}
